var express = require('express');
var router = express.Router();

var db = require("lowdb")('config/db.json');
db.defaults({ heroes: [], userid: 1 }).value();

router.get('/', function(req, res, next) {
    console.log("Post Data Is [ %j ] [ %j ]", req.body, req.query);

    var data = db.get('heroes').value();
    res.json(data);
});

router.all("/addHero", function(req, res, next) {
    var name = req.body.name || req.query.name;

    console.log("addHero Post Data Is [ %j ] [ %j ]", req.body, req.query);

    var id = db.get("userid").value();
    db.set("userid", id + 1).value();

    db.get("heroes").push({ "id": id, "name": name }).value();
    var hero = db.get("heroes").find({ "id": id }).value();

    res.json(hero);
});
router.all("/updateHero", function(req, res, next) {
    var id = req.body.id || req.query.id;
    var name = req.body.name || req.query.name;

    console.log("updateHero Post Data Is [ %j ] [ %j ]", req.body, req.query);

    var hero = db.get("heroes").find({ "id": parseInt(id) }).assign({ "name": name }).value();

    res.json(hero);
});
router.all("/removeHero", function(req, res, next) {
    var id = req.body.id || req.query.id;

    console.log("removeHero Post Data Is [ %j ] [ %j ]", req.body, req.query);

    var hero = db.get("heroes").remove({ "id": parseInt(id) }).value();

    res.json(hero);
});

module.exports = router;